A structure's data is directly accessible to a program. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="6.5 Implementing a Time Abstract Data Type with a Class">
<page>
<font size=18 bold>6.5 Implementing a Time Abstract Data
Type with a Class</font><hr>
Classes enable the programmer to model objects that
have <i>attributes</i> (represented as <i>data members</i>) and
<i>behaviors</i> or <i>operations</i> (represented as <i>member
functions</i>). Types containing data members and member
functions are defined in C++ using the keyword <b>class</b>.<br>
<spacer width=16 height=1>Member functions are sometimes called <i>methods</i> in
other object-oriented programming languages, and are
invoked in response to <i>messages</i> sent to an object. A
message corresponds to a member-function call sent <br>
</page>
<page>
from one object to another or sent from a function to an
object.<br>
<spacer width=16 height=1>Once a class has been defined, the class name can be
used to declare objects of that class. <a href="^Code::c:s0p1"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 6.2</a>
contains a simple definition for class <b>Time</b>.<br>
<spacer width=16 height=1>Our <b>Time</b> class definition begins with the keyword
<b>class</b>. The <i>body</i> of the class definition is delineated with
left and right braces (<b>{</b> and <b>}</b>). <a href="^Errors::c:s0p2"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>The class definition
terminates with a semicolon. Our <b>Time</b> class definition
and our <b>Time</b> structure definition each contain the three
integer members <b>hour</b>, <b>minute</b>, and <b>second</b>. <br>
<spacer width=16 height=1>The remaining parts of the class definition are new. The
<b>public:</b> and <b>private:</b> labels are called <i>member access</i> <br>
</page>
<page>
<i>specifiers</i>. Any data member or member function
declared after member access specifier <b>public</b> (and
before the next member access specifier) is accessible
wherever the program has access to an object of class
<b>Time</b>. Any data member or member function declared
after member access specifier <b>private</b> (and up to the
next member access specifier) is accessible only to
member functions of the class. <a href="^Practice::c:s0p0"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>Member access
specifiers are always followed by a colon (<b>:</b>) and can
appear multiple times and in any order in a class
definition. For the remainder of the text, we will refer to
the member access specifiers as <b>public</b> and <b>private</b>
(without the colon). In Chapter 9 we introduce a third <br>
</page>
<page>
member access specifier, <b>protected</b>, as we study
inheritance and the part it plays in object-oriented
programming.<br>
<spacer width=16 height=1>The class definition contains prototypes for the
following four member functions after the <b>public</b>
member access specifier--<b>Time</b>, <b>setTime</b>,
<b>printMilitary</b>, and <b>printStandard</b>. These are the
<b><i>public</i></b> <i>member functions</i>, or <b><i>public</i></b> <i>services</i>, or <b><i>public</i></b>
<i>behaviors</i> or <i>interface</i> of the class. These functions will
be used by <i>clients</i> (i.e., portions of a program that are
users) of the class to manipulate the data of the class. <br>
<spacer width=16 height=1>Notice the member function with the same name as the
class; it is called a <i>constructor</i> function of that class. A <br>
</page>
<page>
constructor is a special member function that initializes
the data members of a class object. A class's
constructor function is called automatically when an
object of that class is created. We will see that it is
common to have several constructors for a class; this is
accomplished through function overloading. <a href="^Errors::c:s0p3"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>Note that
no return type is specified for the constructor.<br>
<spacer width=16 height=1>The three integer members appear after the <b>private</b>
member access specifier. This indicates that these data
members of the class are only accessible to member
functions--and, as we will see in the next chapter,
"friends"--of the class. Thus, the data members can
only be accessed by the four functions whose <br>
</page>
<page>
prototypes appear in the class definition (or by friends
of the class). Data members are normally listed in the
<b>private</b> portion of a class and member functions are
normally listed in the <b>public</b> portion. It is possible to
have <b>private</b> member functions and <b>public</b> data as we
will see later; the latter is uncommon and is considered
a poor programming practice.<br>
<spacer width=16 height=1>Once the class has been defined, it can be used as a type
in declarations as follows:<br>
<font size=2><br></font><font size=11><pre>
Time sunset,<p>
// object of type Time<p>
arrayOfTimes[ 5 ], <p>
// array of Time objects<p>
*pointerToTime,<p><p>
</pre></font>
</page>
<page>
<font size=2><br></font><font size=11><pre>
// pointer to a Time object<p>
&dinnerTime = sunset;<p>
// reference to a Time object<p>
</pre></font>
The class name becomes a new type specifier. There
may be many objects of a class, just as there may be
many variables of a type such as int. The programmer
can create new class types as needed. This is one reason
why C++ is said to be an <i>extensible language</i>.<br>
<spacer width=16 height=1><a href="^Code::c:s0p2"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 6.3</a> uses the <b>Time</b> class. The program
instantiates a single object of class <b>Time</b> called <b>t</b>. When
the object is instantiated, the <b>Time</b> constructor is called
automatically and explicitly initializes each <b>private</b>
data member to <b>0</b>. The time is then printed in military <br>
</page>
<page>
and standard formats to confirm that the members have
been initialized properly. The time is then set using the
<b>setTime</b> member function and is printed again in both
formats. Then <b>setTime</b> attempts to set the data
members to invalid values, and the time is again printed
in both formats.<br>
Again, note that the data members <b>hour</b>, <b>minute</b>, and
<b>second</b> are preceded by the <b>private</b> member access
specifier. A class's <b>private</b> data members are normally
not accessible outside the class. (Again, we will see in
Chapter 7 that friends of a class may access the class's
<b>private</b> members.) The philosophy here is that the actual
data representation used within the class is of no <br>
</page>
<page>
concern to the class's clients. For example, it would be
perfectly reasonable for the class to represent the time
internally as the number of seconds since midnight.
Clients could use the same <b>public</b> member functions
and get the same results without being aware of this. In
this sense, the implementation of a class is said to be
<i>hidden</i> from its clients. <a href="^Engineer::c:s0p3"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>Such <i>information hiding</i>
promotes program modifiability and simplifies the
client's perception of a class. <br>
<spacer width=16 height=1>In this program, the <b>Time</b> constructor simply initializes
the data members to 0 (i.e., the military time equivalent
of 12 AM). This ensures that the object is in a
consistent state when it is created. <a href="^Engineer::c:s0p5"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>Invalid values cannot <br>
</page>
<page>
be stored in the data members of a <b>Time</b> object because
the constructor is automatically called when the <b>Time</b>
object is created and all subsequent attempts by a client
to modify the data members are scrutinized by function
<b>setTime</b>.<br>
<spacer width=16 height=1> <a href="^Errors::c:s0p4"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>Note that the data members of a class cannot be
initialized where they are declared in the class body.
These data members should be initialized by the class's
constructor, or they can be assigned values by "set"
functions.<br>
<spacer width=16 height=1>A function with the same name as the class but
preceded with a <i>tilde character (~)</i> is called the
<i>destructor</i> of that class (this example does not explicitly <br>
</page>
<page>
include a destructor so the system "plugs one in" for
you). The destructor does "termination housekeeping"
on each class object before the memory for the object is
reclaimed by the system. Destructors cannot take
arguments and hence cannot be overloaded. We will
discuss constructors and destructors in more detail later
in this chapter and in Chapter 7.<br>
<spacer width=16 height=1>Note that the functions the class provides to the outside
world are preceded by the <b>public</b> label. The <b>public</b>
functions implement the behaviors or services the class
provides to its clients--commonly referred to as the
<a href="^Engineer::c:s0p8"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>class's <i>interface</i> or <b><i>public</i></b> <i>interface</i>. <br>
</page>
<page>
The class definition contains declarations of the class's
data members and the class's member functions. The
member function declarations are the function
prototypes we discussed in earlier chapters. Member
functions can be defined inside a class, <a href="^Engineer::c:s0p9"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>but it is a good
programming practice to define the functions outside
the class definition.<br>
<spacer width=16 height=1>Note the use of the <i>binary scope resolution operator(<tt><b>::</b>)</tt></i>
in each member function definition following the class
definition in <a href="^Code::c:s0p2"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 6.3</a>. Once a class is defined and its
member functions are declared, the member functions
must be defined. Each member function of the class can
be defined directly in the class body (rather than <br>
</page>
<page>
including the function prototype of the class), or the
member function can be defined after the class body.
<a href="^Errors::c:s0p5"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>When a member function is defined after its
corresponding class definition, the function name is
preceded by the class name and the binary scope
resolution operator (<b>::</b>). Because different classes can
have the same member names, the scope resolution
operator "ties" the member name to the class name to
uniquely identify the member functions of a particular
class. <br>
<spacer width=16 height=1>Even though a member function declared in a class
definition may be defined outside that class definition,
that member function is still within that <i>class's scope</i>, <br>
</page>
<page>
i.e., its name is known only to other members of the
class unless referred to via an object of the class, a
reference to an object of the class, or a pointer to an
object of the class. We will say more about class scope
shortly.<br>
<spacer width=16 height=1> <a href="^Perform::c:s0p1"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>If a member function is defined in a class definition,
the member function is automatically inlined. <a href="^Engineer::c:s0p11"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>Member
functions defined outside a class definition may be
made inline by explicitly using the keyword <b>inline</b>.
Remember that the compiler reserves the right not to
inline any function.<br>
<spacer width=16 height=1>It is interesting that the <b>printMilitary</b> and
<b>printStandard</b> member functions take no arguments. <br>
</page>
<page>
This is because member functions implicitly know that
they are to print the data members of the particular
<b>Time</b> object for which they are invoked. <a href="^Engineer::c:s0p12"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>This makes
member function calls more concise than conventional
function calls in <a href="^Debug::c:s0p0"><img src="bckgrnds/icons/dbt_ico.gif" align=sidebar></a>procedural programming. <br>
<spacer width=16 height=1>Classes simplify programming because the client (or
user of the class object) need only be concerned with
the operations encapsulated or embedded in the object.
Such operations are usually designed to be client-
oriented rather than implementation-oriented. Clients
need not be concerned with a class's implementation
(although the client, of course, wants a correct and
efficient implementation). <a href="^Engineer::c:s0p14"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>Interfaces do change, but <br>
</page>
<page>
less frequently than implementations. When an
implementation changes, implementation-dependent
code must change accordingly. By hiding the
implementation we eliminate the possibility of other
program parts becoming dependent on the details of the
class implementation.<br>
<spacer width=16 height=1>Often, classes do not have to be created "from scratch."
Rather, they may be <i>derived</i> from other classes that
provide attributes and behaviors the new classes can
use. Or classes can include objects of other classes as
members. Such <i>software reuse</i> can greatly enhance
programmer productivity. Deriving new classes from
existing classes is called <i>inheritance</i> and is discussed in <br>
</page>
<page>
detail in Chapter 9. Including class objects as members
of other classes is called <i>composition</i> and is discussed
in Chapter 7.<br>
<spacer width=16 height=1>People new to object-oriented programming often
express concern at the fact that objects must be quite
large because they contain data and functions.
Logically, this is true--the programmer may think of
objects as containing data and functions. <a href="^Perform::c:s0p3"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>Physically,
however, this is not true.<br>
</page>
<page>
<b>Select the true statement(s). </b><br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. All member functions have class scope.">
A member function defined outside of the class where it is declared does not have class scope. <br>
Operators . and -> are used to access class members. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="6.7 Separating Interface from Implementation">
<page>
<font size=18 bold>6.7 Separating Interface from Implementation</font><hr>
One of the fundamental principles of good software
engineering is to separate interface from
implementation. <a href="^Engineer::c:s0p19"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>This makes it easier to modify
programs. As far as clients of a class are concerned,
changes in the <a href="^Engineer::c:s0p16"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>class's implementation do not affect the
client as long as the class's interface originally provided
to the client is unchanged (the class's functionality
could be expanded beyond the original interface). <br>
<spacer width=16 height=1>Actually, things are not quite this rosy. Header files do
contain some portion of the implementation and hints <br>
</page>
<page>
about other portions of the implementation. Inline
member functions, for example, need to be in a header
file, so that when the compiler compiles a client, the
client can include the <b>inline</b> function definition in
place. <a href="^Engineer::c:s0p21"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>Private members are listed in the class definition
in the header file, so these members are visible to
clients even though the clients may not access the
<b>private</b> members. In Chapter 7, we show how to use a
so-called <i>proxy class</i> to hide even the <b>private</b> data of a
class from clients of the class.<br>
<spacer width=16 height=1> <a href="^Code::c:s0p4"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 6.5</a> splits the program of <a href="^Code::c:s0p2"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 6.3</a> into multiple
files. When building a C++ program, each class
definition is normally placed in a <i>header file</i>, and that <br>
</page>
<page>
class's member function definitions are placed in
<i>source-code files</i> of the same base name. The header
files are included (via <b>#include</b>) in each file in which
the class is used, and the source-code file is compiled
and linked with the file containing the main program.
See your compiler's documentation to determine how
to compile and link programs consisting of multiple
source files.<br>
<spacer width=16 height=1><a href="^Code::c:s0p4"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 6.5</a> consists of the header file <b>time1.h</b> in which
class <b>Time</b> is declared, the file <b>time1.cpp</b> in which the
member functions of class <b>Time</b> are defined, and the
file f<b>ig06_05.cpp</b> in which function <b>main</b> is defined. <br>
</page>
<page>
The output for this program is identical to the output of
Each class definition is normally placed in a header file. <br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. Header files need to be included.">
Header files written by a programmer do not require the use of the preprocessor directive #include. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="6.8 Controlling Access to Members ">
<page>
<font size=18 bold>6.8 Controlling Access to Members </font><hr>
The member access specifiers <b>public</b> and <b>private</b> (and
<b>protected</b> as we will see in Chapter 9, "Inheritance")
are used to control access to a class's data members and
member functions. <a href="^Practice::c:s0p4"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>The default access mode for classes
is <b>private</b> so all members after the class header and
before the first label are <b>private</b>. After each label, the
mode that was invoked by that label applies until the
next label or until the terminating right brace (<b>}</b>) of the
class definition. <a href="^Practice::c:s0p2"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>The labels <b>public</b>, <b>private</b>, and
<b>protected</b> may be repeated, but such usage is rare and
can be confusing.<br>
</page>
<page>
A class's <b>private</b> members can be accessed only by
member functions (and <b>friends</b>, as we will see in
Chapter 7) of that class. The <b>public</b> members of a class
may be accessed by any function in the program.<br>
<spacer width=16 height=1>The primary purpose of <b>public</b> members is to present to
the class's clients a view of the <i>services</i> (behaviors) the
class provides. This set of services forms the <b><i>public</i></b>
<i>interface</i> of the class. Clients of the class need not be
concerned with how the class accomplishes its tasks.
<a href="^Errors::c:s0p6"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>The <b>private</b> members of a class as well as the
definitions of its <b>public</b> member functions are not
accessible to the clients of a class. These components
<a href="^Engineer::c:s0p23"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>form the <i>implementation</i> of the class. <br>
</page>
<page>
<a href="^Code::c:s0p5">F <img src="bckgrnds/icons/code_ico.gif" align=sidebar>igure 6.6</a> demonstrates that <b>private</b> class members
are only accessible through the <b>public</b> class interface
using <b>public</b> <a href="^Engineer::c:s0p25"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>member functions. When this program is
compiled, the compiler generates two errors stating that
the <b>private</b> member specified in each statement is not
accessible. <a href="^Code::c:s0p5"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 6.6</a> includes <b>time1.h</b> and is compiled
with <b>time1.cpp</b> from <a href="^Code::c:s0p4"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 6.5</a>.<br>
<spacer width=16 height=1>A client of a class may be a member function of another
class or it may be a global function (i.e., a C-like
"loose" function in the file that is not a member
function of any class).<br>
<spacer width=16 height=1>The default access for members of a class is <b>private</b>.
Access to members of a class may be explicitly set to <br>
</page>
<page>
<b>public</b>, <b>protected</b> (as we will see in Chapter 9), or
<b>private</b>. The default access for struct members is
<b>public</b>. Access to members of a <b>struct</b> also may be
explicitly set to <b><img src="bckgrnds/icons/seo_ico.gif" align=sidebar>public</b>, <b>protected</b>, or <b>private</b>. <br>
<spacer width=16 height=1>Just because class data is <b>private</b> does not necessarily
mean that clients cannot effect changes to that data. The
data can be changed by member functions or <tt><b>friend</b></tt>s of
that class. As we will see, these functions should be
designed to ensure the integrity of the data. <br>
<spacer width=16 height=1><a href="^Debug::c:s0p3"><img src="bckgrnds/icons/dbt_ico.gif" align=sidebar></a>Access to a class's <b>private</b> data should be carefully
controlled by the use of member functions, called
<i>access functions</i> (also called <i>accessor methods</i>). For
example, to allow clients to read the value of <b>private</b> <br>
</page>
<page>
data, the class can provide a <i>get</i> function. To enable
clients to modify <tt><b>private</b></tt> data, the class can provide
a <i>set</i> function. Such modification would seem to violate
the notion of <b>private</b> data. <a href="^Engineer::c:s0p28"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>But a <i>set</i> member function
can provide data validation capabilities (such as range
checking) to ensure that the value is set properly. A <i>set</i>
function can also translate between the form of the data
used in the interface and the form used in the
implementation. A <i>get</i> function need not expose the
data in "raw" format; rather the <i>get</i> function can edit the
data and limit the view of the data the client will see.<br>
Access to members of a struct can be designated public, protected, or private. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="6.9 Access Functions and Utility Functions">
<page>
<font size=18 bold>6.9 Access Functions and Utility Functions</font><hr>
Not all member functions need be made <b>public</b> to serve
as part of the interface of a class. <a href="^Engineer::c:s0p29"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>Some member
functions remain <b>private</b> and serve as <i>utility functions</i>
to the other functions of the class.<br>
<spacer width=16 height=1>Access functions can read or display data. Another
common use for access functions is to test the truth or
falsity of conditions--such functions are often called
<i>predicate functions</i>. An example of a predicate function
would be an <b>isEmpty</b> function for any container
class--a class capable of holding many objects--such
as a linked list, a stack or a queue. A program would <br>
</page>
<page>
test <b>isEmpty</b> before attempting to read another item
from the container object. An <b>isFull</b> predicate function
might test a container class object to determine if it has
no additional room. A set of useful predicate functions
for our <b>Time</b> class might be <b>isAM</b> and <b>isPM</b>.<br>
<spacer width=16 height=1><a href="^Code::c:s0p6"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 6.7</a> demonstrates the notion of a <i>utility function</i>
(also called a <i>helper function</i>). A utility function is not
part of a class's interface; rather, it is a <b>private</b> member
function that supports the operation of the class's
<b>public</b> member functions. Utility functions are not
intended to be used by clients of a class. <br>
<spacer width=16 height=1>Class <b>SalesPerson</b> has an array of 12 monthly sales
figures initialized by the constructor to zero and set to <br>
</page>
<page>
user-supplied values by function <b>setSales</b>. Public
member function <b>printAnnualSales</b> prints the total
sales for the last 12 months. Utility function
<b>totalAnnualSales</b> totals the 12 monthly sales figures
for the benefit of <b>printAnnualSales</b>. Member function
<b>printAnnualSales</b> edits the sales figures into dollar
amount format. <br>
<spacer width=16 height=1><a href="^Engineer::c:s0p32"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>Note that <b>main</b> includes only a simple sequence of
member function calls--there are no control structures.<br>
Functions that return boolean values are often referred to as predicate functions. <br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. Utility functions are for use by other member functions of the class.">
Utility functions are designed to called by clients of the class. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="6.10 Initializing Class Objects: Constructors">
<page>
<font size=18 bold>6.10 Initializing Class Objects: Constructors</font><hr>
When a class object is created, its members can be
initialized by that class's <i>constructor</i> function. A
constructor is a class member function with the same
name as the class. <a href="^Practice::c:s0p6"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>The programmer provides the
constructor which is then invoked automatically each
<a href="^Debug::c:s0p5"><img src="bckgrnds/icons/dbt_ico.gif" align=sidebar></a>time an object of that class is created (instantiated).
Constructors may be overloaded to provide a variety of
means for initializing objects of a class. <a href="^Errors::c:s0p7"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>Data members
must either be initialized in a constructor of the class, or
<a href="^Errors::c:s0p8"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>their values may be <i>set</i> later after the object is created. <br>
</page>
<page>
When an object of a class is declared, <i>initializers</i> can be
provided in parentheses to the right of the object name
and before the semicolon. These initializers are passed
as arguments to the class's constructor. We will soon
see several examples of these <i>constructor calls</i>. [Note:
Although programmers do not explicitly call
constructors, programmers can still provide data that
A constructor is a member function with the same name as the class. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="6.11 Using Default Arguments with Constructors">
<page>
<font size=18 bold>6.11 Using Default Arguments with Constructors</font><hr>
The constructor from <b>time1.cpp</b> ( <a href="^Code::c:s0p4"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 6.5</a>) initialized
<b>hour</b>, <b>minute</b>, and <b>second</b> to <b>0</b> (i.e., 12 midnight in
military time). Constructors can contain default
arguments. <a href="^Code::c:s0p7"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 6.8</a> redefines the <b>Time</b> constructor
function to include default arguments of zero for each
variable. By providing default arguments to the
constructor, even if no values are provided in a
constructor call, the object is still guaranteed to be
initialized to a consistent state due to the default
arguments. A programmer-supplied constructor that <br>
</page>
<page>
defaults all its arguments (or explicitly requires no
arguments) is also a <i>default constructor</i>, i.e., a
constructor that can be invoked with no arguments.
There can be only one default constructor per class. <br>
In this program, the constructor calls member function
<b>setTime</b> with the values passed to the constructor (or
the default values) to ensure that the value supplied for
<b>hour</b> is in the range 0 to 23, and that the values for
<b>minute</b> and <b>second</b> are each in the range 0 to 59. If a
value is out of range, it is set to zero by <b>setTime</b> (this is
an example of ensuring that a data member remains in a
consistent state). <br>
</page>
<page>
Note that the <b>Time</b> constructor could be written to
include the same statements as member function
<b>setTime</b>. This may be slightly more efficient because
the extra call to <b>setTime</b> is eliminated. However,
coding the <b>Time</b> constructor and member function
<b>setTime</b> identically makes maintenance of this program
more difficult. If the implementation of member
function <b>setTime</b> changes, the implementation of the
<b>Time</b> constructor should change accordingly. Having
the <b>Time</b> constructor call <b>setTime</b> directly, requires any
changes to the implementation of <b>setTime</b> to be made
only once. <a href="^Engineer::c:s0p34"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>This reduces the likelihood of a
programming error when altering the implementation. <br>
</page>
<page>
Also, the performance of the <b>Time</b> constructor can be
enhanced by explicitly declaring the constructor <b>inline</b>
or by defining <a href="^Errors::c:s0p9"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>the constructor in the class definition
(which implicitly <b>inlines</b> the <b><a href="^Practice::c:s0p8"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a></b>function definition).<br>
<spacer width=16 height=1>The program of <a href="^Code::c:s0p7"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 6.8</a> initializes five <b>Time</b> objects--
one with all three arguments defaulted in the
constructor call, one with one argument specified, one
with two arguments specified, one with three arguments
specified, and one with three invalid arguments
specified. The contents of each object's data members
after instantiation and initialization are displayed. <br>
<spacer width=16 height=1> <a href="^Engineer::c:s0p36"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>If no constructor is defined for a class, the compiler
creates a default constructor. Such a constructor does <br>
</page>
<page>
not perform any initialization, so when the object is
created, it is not guaranteed to be in a consistent state. <br>
Constructors can contain provide default arguments in the parameter list. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="6.12 Using Destructors">
<page>
<font size=18 bold>6.12 Using Destructors</font><hr>
A <b>destructor</b> is a special member function of a class.
The name of the destructor for a class is the <i>tilde</i> (<b>~</b>)
character followed by the class name. This naming
convention has intuitive appeal, because as we will see
in a later chapter the tilde operator is the bitwise
complement operator, and, in a sense, the destructor is
the complement of the constructor. <br>
<spacer width=16 height=1>A class's destructor is called when an object is
destroyed--e.g., when program execution leaves the
scope in which an object of that class was instantiated.
The destructor itself does not actually destroy the <br>
</page>
<page>
object--it performs <i>termination housekeeping</i> before
the system reclaims the object's memory so that
memory may be reused to hold new objects.<br>
<spacer width=16 height=1><a href="^Errors::c:s0p10"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>A destructor receives no parameters and returns no
value. A class may have only one destructor--
destructor overloading is not allowed.<br>
<spacer width=16 height=1><a href="^Engineer::c:s0p37"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>Notice that destructors have not been provided for the
classes presented so far. We will soon see several
examples of classes with useful destructors. In Chapter
8, we will see that destructors are appropriate for
A destructor is called when an object is removed from memory. <br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. A destructor cannot take arguments.">
Like a constructor, a destructor can take arguments. <br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. A destructor cannot return a value.">
A destructor may return a value. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="6.13 When Constructors and Destructors are Called">
<page>
<font size=18 bold>6.13 When Constructors and Destructors are
Called</font><hr>
Constructors and destructors are called automatically.
The order in which these function calls are made
depends on the order in which execution enters and
leaves the scope in which objects are instantiated.
Generally, destructor calls are made in the reverse order
of the constructor calls. However, as we will see in <a href="^Code::c:s0p8"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig.
6.9</a>, the storage class of objects can alter the order in
which the destructors are called.<br>
<spacer width=16 height=1>Constructors are called for objects defined in global
scope before any other function (including <b>main</b>) in <br>
</page>
<page>
that file begins execution (although the order of
execution of global object constructors between files is
not guaranteed). The corresponding destructors are
called when <b>main</b> terminates or the <b>exit</b> function (see
Chapter 18, "Other Topics") is called.<br>
<spacer width=16 height=1>Constructors are called for automatic local objects
when execution reaches the point where the objects are
defined. The corresponding destructors are called when
the objects leave scope (i.e., the block in which they are
defined is exited). Constructors and destructors for
automatic objects are called each time the objects enter
and leave scope.<br>
</page>
<page>
Constructors are called for <b>static</b> local objects only
once when execution first reaches the point where the
objects are defined. Corresponding destructors are
called when <b>main</b> terminates or the <b>exit</b> function is
called.<br>
<spacer width=16 height=1>The program of <a href="^Code::c:s0p8"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 6.9</a> demonstrates the order in
which constructors and destructors are called for
objects of type <b>CreateAndDestroy</b> in several scopes.
The program defines <b>first</b> in global scope. Its
constructor is called as the program begins execution
and its destructor is called at program termination after
all other objects are destroyed. <br>
</page>
<page>
Function <b>main</b> declares three objects. Objects <b>second</b>
and <b>fourth</b> are local automatic objects, and object <b>third</b>
is a <b>static</b> local object. The constructors for each of
these objects are called when execution reaches the
point where each object is declared. The destructors for
objects <b>fourth</b> and <b>second</b> are called in that order when
the end of <b>main</b> is reached. Because object <b>third</b> is
<b>static</b>, it exists until program termination. The
destructor for object <b>third</b> is called before the
destructor for <b>first</b>, but after all other objects are
destroyed. <br>
<spacer width=16 height=1>Function <b>create</b> declares three objects--<b>fifth</b> and
<b>seventh</b> are local automatic objects, and <b>sixth</b> is a <br>
</page>
<page>
<b>static</b> local object. The destructors for objects <b>seventh</b>
and <b>fifth</b> are called in that order when the end of <b>create</b>
is reached. Because <b>sixth</b> is <b>static</b>, it exists until
program termination. The destructor for <b>sixth</b> is called
before the destructors for <b>third</b> and <b>first</b>, but after all
In general, destructor calls are made in the reverse order of constructor calls. <br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. A programmer can provide a constructor or destructor as required for a class. If not provided, the compiler provides default definitions of each.">
The programmer must always provide a constructor and destructor for a class. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="6.14 Using Data Members and Member Functions">
<page>
<font size=18 bold>6.14 Using Data Members and Member
Functions</font><hr>
A class's <b>private</b> data members can be manipulated
only by member functions (and <b>friend</b>s) of the class. A
typical manipulation might be the adjustment of a
customer's bank balance (e.g., a <b>private</b> data member
of a class <b>BankAccount</b>) by a member function
<b>computeInterest</b>. <br>
<spacer width=16 height=1>Classes often provide <b>public</b> member functions to
allow clients of the class to <i>set</i> (i.e., write) or <i>get</i> (i.e.,
read) the values of <b>private</b> data members. These
functions need not be called <i>set</i> and <i>get</i> specifically, but <br>
</page>
<page>
they often are. More specifically, a member function
that <i>sets</i> data member <b>interestRate</b> would typically be
named <b>setInterestRate</b>, and a member function that
<i>gets</i> the <b>interestRate</b> would typically be called
<b>getInterestRate</b>. Get functions are also commonly
called "query" functions.<br>
<spacer width=16 height=1>It may seem that providing both <i>set</i> and <i>get</i> capabilities
is essentially the same as making the data members
<b>public</b>. This is yet another subtlety of C++ that makes
the language so desirable for software engineering. If a
data member is <b>public</b>, then the data member may be
read or written at will by any function in the program. If
a data member is <b>private</b>, a <tt><b>public</b></tt> <i>get</i> function <br>
</page>
<page>
would certainly seem to allow other functions to read
the data at will but the <i>get</i> function could control the
formatting and display of the data. <a href="^Practice::c:s0p9"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>A <tt><b>public</b></tt> <i>set</i>
function could--and most likely would--carefully
scrutinize any attempt to modify the value of the data
member. <a href="^Engineer::c:s0p39"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>This would ensure that the new value is
appropriate for that data item. <a href="^Debug::c:s0p6"><img src="bckgrnds/icons/dbt_ico.gif" align=sidebar></a>For example, an attempt
to <i>set</i> the day of the month to 37 could be rejected, an
attempt to <i>set</i> a person's weight to a negative value
could be rejected, an attempt to <i>set</i> a numeric quantity
to an alphabetic value could be rejected, an attempt to
<i>set</i> a grade on an exam to 185 (when the proper range is
zero to 100) could be rejected, etc. <br>
</page>
<page>
The client of a class should be notified when an attempt
is made to assign an invalid value to a data member. A
class's <i>set</i> functions are often written to return values
indicating that an attempt was made to assign invalid
data to an object of the class. This enables clients of the
class to test the return values of <i>set</i> functions to
determine if the object they are manipulating is a valid
object and to take appropriate action if the object is not
<spacer width=16 height=1><a href="^Code::c:s0p9"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 6.10</a> extends our <b>Time</b> class to include <i>get</i> and
<i>set</i> functions for the <b>hour</b>, <b>minute</b>, and <b>second</b> <b>private</b>
data members. The <i>set</i> functions strictly control the
setting of the data members. Attempts to <i>set</i> any data <br>
</page>
<page>
member to an incorrect value cause the data member to
be set to zero (thus leaving the data member in a
consistent state). Each <i>get</i> function simply returns the
appropriate data member's value. The program first
uses the <i>set</i> functions to <i>set</i> the <b>private</b> data members
of <b>Time</b> object t to valid values, then uses the <i>get</i>
functions to retrieve the values for output. Next the <i>set</i>
functions attempt to <i>set</i> the <b>hour</b> and <b>second</b> members
to invalid values and the <b>minute</b> member to a valid
value, and then the <i>get</i> functions retrieve the values for
output. The output confirms that invalid values cause
the data members to be <i>set</i> to zero. Finally, the program
<i>sets</i> the time to <b>11:58:00</b> and increments the minute <br>
</page>
<page>
value by 3 with a call to function <b>incrementMinutes</b>.
Function <b>incrementMinutes</b> is a nonmember function
that uses the <i>get</i> and <i>set</i> member functions to increment
the <b>minute</b> member properly. Although this works, it
incurs the performance burden of issuing multiple
function calls. In the next chapter, we discuss the notion
of <b>friend</b> functions as a means of eliminating this
performance burden.<br>
Using <i>set</i> functions is certainly important from a
A set function should perform validity checking. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="6.15 A Subtle Trap: Returning a Reference to a Private Data Member">
<page>
<font size=18 bold>6.15 A Subtle Trap: Returning a Reference to
a Private Data Member</font><hr>
A reference to an object is an alias for the <i>name</i> of the
object and hence may be used on the left side of an
assignment statement. In this context, the reference
makes a perfectly acceptable <i>lvalue</i> that can receive a
value. <a href="^Practice::c:s0p10"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>One way to use this capability (unfortunately!) is
to have a <b>public</b> member function of a class return a
<b>non-const</b> reference to a <b>private</b> data member of that
class.<br>
<spacer width=16 height=1><a href="^Code::c:s0p10"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 6.11</a> uses a simplified <b>Time</b> class to demonstrate
returning a reference to a <b>private</b> data member. Such a <br>
</page>
<page>
return actually makes a call to function <b>badSetHour</b> an
alias for the <b>private</b> data member <b>hour</b>! The function
call can be used in any way that the <b>private</b> data
member can be used, including as an <i>lvalue</i> in an
assignment statement! <br>
The program begins by declaring <b>Time</b> object <b>t</b> and
reference <b>hourRef</b> that is assigned the reference
returned by the call <b>t.badSetHour(20)</b>. The program
displays the value of the alias <b>hourRef</b>. Next, the alias
is used to set the value of <b>hour</b> to 30 (an invalid value)
and the value is displayed again. Finally, the function
call itself is used as an <i>lvalue</i> and assigned the value 74
(another invalid value), and the value is displayed.<br>
</page>
</section>
<section type=Body name=Default title="6.16 Assignment by Default Memberwise Copy">
<page>
<font size=18 bold>6.16 Assignment by Default Memberwise
Copy</font><hr>
The assignment operator (<b>=</b>) can be used to assign an
object to another object of the same type. Such
assignment is by default performed by <i>memberwise
copy</i>--each member of one object is copied
individually to the same member in another object (see
<a href="^Code::c:s0p11"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 6.12</a>). (Note: Memberwise copy can cause serious
problems when used with a class whose data members
contain dynamically allocated storage; in Chapter 8,
"Operator Overloading," we will discuss these
problems and show how to deal with them.)<br>
</page>
<page>
Objects may be passed as function arguments and may
be returned from functions. <a href="^Perform::c:s0p6"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>Such passing and returning
is performed call-by-value by default--a copy of the
object is passed or returned (we present several
examples in Chapter 8, "Operator Overloading").<br>
<indent width=8 delay>* Structures are aggregate data types built using data of
other types. </indent>
<indent width=8 delay>* The keyword <b>struct</b> introduces a structure definition.
The body of a structure is delineated by braces (<b>{</b> and <b>}</b>).
Every structure definition must end with a semicolon. </indent>
<indent width=8 delay>* A structure tag name can be used to declare variables
of a structure type.</indent>
<indent width=8 delay>* Structure definitions do not reserve space in memory;
they create new data types that are used to declare variables. </indent>
<indent width=8 delay>* Members of a structure or a class are accessed using </indent>
</page>
<page>
<indent width=8 delay>* the member access operators--the dot operator (<b>.</b>) and
the arrow operator (<b>-></b>). The dot operator accesses a
structure member via the object's variable name or a
reference to the object. The arrow operator accesses a
structure member via a pointer to the object. </indent>
<indent width=8 delay>* Drawbacks to creating new data types with <b>struct</b>s
are the possibility of having uninitialized data;
improper initialization; all programs using a <b>struct</b>
must be changed if the <b>struct</b> implementation changes;
and no protection is provided to ensure that data is kept
in a consistent state with proper data values. </indent>
<indent width=8 delay>* Classes enable the programmer to model objects with
attributes and behaviors. Class types can be defined in </indent>
</page>
<page>
<indent width=8 delay>* C++ using the keywords <b>class</b> and <b>struct</b>, but keyword
<b>class</b> is normally used for this purpose.</indent>
<indent width=8 delay>* The class name can be used to declare objects of that
class. </indent>
<indent width=8 delay>* Class definitions begin with the keyword <b>class</b>. The
body of the class definition is delineated with braces (<b>{</b>
and <b>}</b>). Class definitions terminate with a semicolon. </indent>
<indent width=8 delay>* Any data member or member function declared after
<b>public:</b> in a class is visible to any function with access
to an object of the class.</indent>
<indent width=8 delay>* Any data member or member function declared after
<b>private: </b>is only visible to <b>friend</b>s and other members
of the class. </indent>
</page>
<page>
<indent width=8 delay>* Member access specifiers always end with a colon (<b>:</b>)
and can appear multiple times and in any order in a
class definition.</indent>
<indent width=8 delay>* Private data are not accessible from outside the class. </indent>
<indent width=8 delay>* The implementation of a class should be hidden from
its clients. </indent>
<indent width=8 delay>* A constructor is a special member function with the
same name as the class that is used to initialize the
members of a class object. A class's constructor is
called when an object of that class is instantiated. </indent>
<indent width=8 delay>* The function with the same name as the class but preceded with a tilde character (<b>~</b>) is called a destructor. </indent>
<indent width=8 delay>* The set of <b>public</b> member functions of a class is </indent>
</page>
<page>
<indent width=8 delay>* called the class's interface or <b>public</b> interface.</indent>
<indent width=8 delay>* When a member function is defined outside the class
definition, the function name is preceded by the class
name and the binary scope resolution operator (<b>::</b>). </indent>
<indent width=8 delay>* Member functions defined using the scope resolution
operator outside a class definition are within that class's
scope.</indent>
<indent width=8 delay>* Member functions defined in a class definition are
automatically inlined. The compiler reserves the right
not to inline any function.</indent>
<indent width=8 delay>* Calling member functions is more concise than calling functions in procedural programming because most
data used by the member function is directly accessible </indent>
</page>
<page>
<indent width=8 delay>* in the object.</indent>
<indent width=8 delay>* Within a class's scope, class members may be referenced simply by their names. Outside a class's scope,
class members are referenced through either an object
name, a reference to an object, or a pointer to an object. </indent>
<indent width=8 delay>* Member selection operators <b>.</b> and <b>-></b> are used to
access class members.</indent>
<indent width=8 delay>* A fundamental principle of good software engineering is to separate interface from implementation. </indent>
<indent width=8 delay>* Class definitions are normally placed in header files
and member function definitions are normally placed in
source-code files of the same base name.</indent>
<indent width=8 delay>* The default access mode for classes is <b>private</b> so all </indent>
</page>
<page>
<indent width=8 delay>* members after the class header and before the first
member access specifier are considered to be <b>private</b>. </indent>
<indent width=8 delay>* A class's <b>public</b> members present a view of the services the class provides to the clients of the class. </indent>
<indent width=8 delay>* Access to a class's <b>private</b> data can be carefully controlled by the use of member functions called access
functions. If a class wants to allow clients to read <b>private</b> data, the class can provide a <i>get</i> function. To
enable clients to modify <b>private</b> data, the class can provide a <i>set</i> function. </indent>
<indent width=8 delay>* Data members of a class are normally made <b>private</b>
and member functions of a class are normally made
<b>public</b>. Some member functions may be <b>private</b> and </indent>
</page>
<page>
<indent width=8 delay>* serve as utility functions to the other functions of the
class.</indent>
<indent width=8 delay>* Data members of a class cannot be initialized in a
class definition. They must be initialized in a constructor, or their values may be <i>set</i> after their object is created.</indent>
<indent width=8 delay>* Constructors can be overloaded. </indent>
<indent width=8 delay>* Once a class object is properly initialized, all member functions that manipulate the object should ensure
that the object remains in a consistent state. </indent>
<indent width=8 delay>* When an object of a class is declared, initializers can
be provided. These initializers are passed to the class's
constructor. </indent>
</page>
<page>
<indent width=8 delay>* Constructors can specify default arguments. </indent>
<indent width=8 delay>* Constructors may not specify return types, nor may
they attempt to return values.</indent>
<indent width=8 delay>* If no constructor is defined for a class, the compiler
creates a default constructor. A default constructor supplied by the compiler does not perform any initialization, so when the object is created, it is not guaranteed
to be in a consistent state.</indent>
<indent width=8 delay>* The destructor of an automatic object is called when
the object goes out of scope. The destructor itself does
not actually destroy the object, but it does perform termination housekeeping before the system reclaims the
object's storage. </indent>
</page>
<page>
<indent width=8 delay>* Destructors do not receive parameters and do not
return values. A class may have only one destructor
(destructors cannot be overloaded).</indent>
<indent width=8 delay>* The assignment operator (<b>=</b>) is used to assign an
object to another object of the same type. Such assignment is normally performed by default memberwise
copy. Memberwise copy is not ideal for all classes.</indent>
a) The keyword _______ introduces a structure definition.<br>
b) Class members are accessed via the _______ operator in conjunction with
the name of an object of the class or via the ________operator in conjunction
with a pointer to an object of the class.<br>
c) Members of a class specified as _______ are accessible only to member
functions of the class and <b>friend</b>s of the class.<br>
d) A _______ is a special member function used to initialize the data members
of a class.<br>
e) The default access for members of a class is _______ .<br>
<foreign name="answers" url="^Answers::c:s0p0">
</page>
<page pagename="Exercise 6.1">
f) A ________function is used to assign values to <b>private</b> data members of a
class.<br>
g) ________ can be used to assign an object of a class to another object of
the same class.<br>
h) Member functions of a class are normally made _______ and data members
of a class are normally made ________.<br>
i) A _______ function is used to retrieve values of <b>private</b> data of a class.<br>
j) The set of <b>public</b> member functions of a class is referred to as the class's
_____.<br>
k) A class implementation is said to be hidden from its clients or ________.<br>
l) The keywords _______ and _______ can be used to introduce a class
definition.<br>
<foreign name="answers" url="^Answers::c:s0p0">
</page>
<page pagename="Exercise 6.1">
m) Members of a class specified as _______ are accessible anywhere an
object of the class is in scope.<br>
<foreign name="answers" url="^Answers::c:s0p0">
<br>
</page>
<page pagename="Exercise 6.2">
<b>Exercise 6.2</b><br>
Find the error(s) in each of the following and explain how to correct it. <br>
a) Assume the following prototype is declared in class <b>Time</b>.<br>
<font size=2><br></font><font size=11><pre>
void ~Time( int );<p>
</pre></font>
b) The following is a partial definition of class <b>Time</b>.<br>
<font size=2><br></font><font size=11><pre>
class Time {<p>
public:<p>
// function prototypes<p>
private:<p>
int hour = 0;<p>
int minute = 0;<p>
</pre></font>
<foreign name="answers" url="^Answers::c:s0p2">
</page>
<page pagename="Exercise 6.2">
<font size=2><br></font><font size=11><pre>
int second = 0;<p>
</pre></font>
<font size=2><br></font><font size=11><pre>
};<p>
</pre></font>
c) Assume the following prototype is declared in class <b>Employee</b>.<br>
<font size=2><br></font><font size=11><pre>
int Employee( const char *, const char * );<p>
</pre></font>
<foreign name="answers" url="^Answers::c:s0p2">
<br>
</page>
<page pagename="Exercise 6.3">
<b>Exercise 6.3</b><br>
What is the purpose of the scope resolution operator?<br>
<br>
</page>
<page pagename="Exercise 6.4">
<b>Exercise 6.4</b><br>
Compare and contrast the notions of <b>struct</b> and <b>class</b> in C++.<br>
<br>
<br>
</page>
<page pagename="Exercise 6.5">
<b>Exercise 6.5</b><br>
Provide a constructor that is capable of using the current time from the <b>time()</b>
function--declared in the C Standard Library header <b>time.h</b>--to initialize an
object of the <b>Time</b> class.<br>
<foreign name="answers" url="^Answers::c:s0p3">
</page>
<page pagename="Exercise 6.6">
<b>Exercise 6.6</b><br>
Create a class called <b>Complex</b> for performing arithmetic with complex numbers.
Write a driver program to test your class. <br>
Complex numbers have the form <br>
<font size=2><br></font><font size=11><pre>
realPart + imaginaryPart * i<p>
</pre></font>
where <i>i</i> is <img src="graphics/ch06/ex06006.gif" ><br>
Use floating-point variables to represent the <b>private</b> data of the class. Provide a
constructor function that enables an object of this class to be initialized when it
is declared. The constructor should contain default values in case no initializers
are provided. Provide <b>public</b> member functions for each of the following:<br>
</page>
<page pagename="Exercise 6.6">
a) Addition of two <b>Complex</b> numbers: The real parts are added together and the
imaginary parts are added together.<br>
b) Subtraction of two <b>Complex</b> numbers: The real part of the right operand is
subtracted from the real part of the left operand and the imaginary part of the
right operand is subtracted from the imaginary part of the left operand.<br>
c) Printing <b>Complex</b> numbers in the form <b>(a, b)</b> where <b>a</b> is the real part and <b>b</b> is
the imaginary part.<br>
<br>
<br>
</page>
<page pagename="Exercise 6.7">
<b>Exercise 6.7</b><br>
Create a class called <b>Rational</b> for performing arithmetic with fractions. Write a
driver program to test your class.<br>
Use integer variables to represent the <b>private</b> data of the class--the numerator
and the denominator. Provide a constructor function that enables an object of
this class to be initialized when it is declared. The constructor should contain
default values in case no initializers are provided and should store the fraction in
reduced form (i.e., the fraction <img src="graphics/ch06/ex06007.gif" ><br>
would be stored in the object as 1 in the numerator and 2 in the denominator).
Provide <b>public</b> member functions for each of the following:<br>
<foreign name="answers" url="^Answers::c:s0p4">
</page>
<page pagename="Exercise 6.7">
a) Addition of two <b>Rational</b> numbers. The result should be stored in reduced
form.<br>
b) Subtraction of two <b>Rational</b> numbers. The result should be stored in reduced
form.<br>
c) Multiplication of two <b>Rational</b> numbers. The result should be stored in
reduced form.<br>
d) Division of two <b>Rational</b> numbers. The result should be stored in reduced
form.<br>
e) Printing <b>Rational</b> numbers in the form <b>a/b</b> where <b>a</b> is the numerator and <b>b</b> is
the denominator.<br>
f) Printing <b>Rational</b> numbers in floating-point format.<br>
<foreign name="answers" url="^Answers::c:s0p4">
</page>
<page pagename="Exercise 6.8">
<b>Exercise 6.8</b><br>
Modify the <b>Time</b> class of<a href="^Code::c:s0p9"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 6.10 </a>to include a <b>tick</b> member function that
increments the time stored in a <b>Time</b> object by one second. The <b>Time</b> object
should always remain in a consistent state. Write a driver program that tests the
<b>tick</b> member function in a loop that prints the time in standard format during
each iteration of the loop to illustrate that the <b>tick</b> member function works
correctly. Be sure to test the following cases:<br>
a) Incrementing into the next minute.<br>
b) Incrementing into the next hour.<br>
c) Incrementing into the next day (i.e., 11:59:59 PM to 12:00:00 AM).<br>
<foreign name="answers" url="^Answers::c:s0p5">
</page>
<page pagename="Exercise 6.9">
<b>Exercise 6.9</b><br>
Modify the <b>Date</b> class of <a href="^Code::c:s0p11"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 6.12</a> to perform error checking on the initializer
values for data members <b>month</b>, <b>day</b>, and <b>year</b>. Also, provide a member
function <b>nextDay</b> to increment the day by one. The <b>Date</b> object should always
remain in a consistent state. Write a driver program that tests the <b>nextDay</b>
function in a loop that prints the date during each iteration of the loop to
illustrate that the <b>nextDay</b> function works correctly. Be sure to test the following
cases:<br>
a) Incrementing into the next month.<br>
b) Incrementing into the next year.<br>
<br>
<br>
</page>
<page pagename="Exercise 6.10">
<b>Exercise 6.10</b><br>
Combine the modified <b>Time</b> class of<a href="^Exercises::c:s0p12"> <img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 6.8</a> and the modified <b>Date</b> class
of<a href="^Exercises::c:s0p13"> <img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 6.9</a> into one class called <b>DateAndTime</b> (in Chapter 9 we will
discuss inheritance which will enable us to accomplish this task quickly without
modifying the existing class definitions). Modify the <b>tick</b> function to call the
<b>nextDay</b> function if the time is incremented into the next day. Modify function
<b>printStandard</b> and <b>printMilitary</b> to output the date in addition to the time.
Write a driver program to test the new class <b>DateAndTime</b>. Specifically test
incrementing the time into the next day.<br>
<br>
<br>
</page>
<page pagename="Exercise 6.11">
<b>Exercise 6.11</b><br>
Modify the <i>set</i> functions in the program of<a href="^Code::c:s0p9"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 6.10</a> to return appropriate error
values if an attempt is made to <i>set</i> a data member of an object of class <b>Time</b> to
an invalid value. <br>
<br>
<br>
</page>
<page pagename="Exercise 6.12">
<b>Exercise 6.12</b><br>
Create a class <b>Rectangle</b>. The class has attributes <b>length</b> and <b>width</b>, each of
which defaults to 1. It has member functions that calculate the <b>perimeter</b> and
the <b>area</b> of the rectangle. It has <i>set</i> and <i>get</i> functions for both <b>length</b> and <b>width</b>.
The <i>set</i> functions should verify that <b>length</b> and <b>width</b> are each floating-point
numbers larger than 0.0 and less than 20.0. <br>
<foreign name="answers" url="^Answers::c:s0p6">
</page>
<page pagename="Exercise 6.13">
<b>Exercise 6.13</b><br>
Create a more sophisticated <b>Rectangle</b> class than the one you created in<a href="$currentLink">
<img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 6.12</a>. This class stores only the Cartesian coordinates of the four
corners of the rectangle. The constructor calls a <i>set</i> function that accepts four
sets of coordinates and verifies that each of these is in the first quadrant with no
single x or y coordinate larger than 20.0. The <i>set</i> function also verifies that the
supplied coordinates do, in fact, specify a rectangle. Member functions calculate
the <b>length</b>, <b>width</b>, <b>perimeter</b>, and <b>area</b>. The length is the larger of the two
dimensions. Include a predicate function <b>square</b> that determines if the rectangle
is a square. <br>
<br>
<br>
</page>
<page pagename="Exercise 6.14">
<b>Exercise 6.14</b><br>
Modify the <b>Rectangle</b> class of <a href="^Exercises::c:s0p17"><img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 6.13</a> to include a <b>draw</b> function that
displays the rectangle inside a 25-by-25 box enclosing the portion of the first
quadrant in which the rectangle resides. Include a <b>setFillCharacter</b> function to
specify the character out of which the body of the rectangle will be drawn.
Include a <b>setPerimeterCharacter</b> function to specify the character that will be
used to draw the border of the rectangle. If you feel ambitious you might include
functions to scale the size of the rectangle, rotate it, and move it around within
the designated portion of the first quadrant.<br>
<br>
<br>
</page>
<page pagename="Exercise 6.15">
<b>Exercise 6.15</b><br>
Create a class <b>HugeInteger</b> that uses a 40-element array of digits to store
integers as large as 40-digits each. Provide member functions
<b>inputHugeInteger</b>, <b>outputHugeInteger</b>, <b>addHugeIntegers</b>, and
<b>substractHugeIntegers</b>. For comparing <b>HugeInteger</b> objects provide functions